package com.shop.cereshop.app.service.buyer.impl;

import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.buyer.BuyerUserBlacklistMapper;
import com.shop.cereshop.app.page.buyer.blacklist.BuyerBlacklistVO;
import com.shop.cereshop.app.param.buyer.blacklist.AddBlacklistParam;
import com.shop.cereshop.app.param.buyer.blacklist.QueryBlacklistDTO;
import com.shop.cereshop.app.param.buyer.blacklist.QueryBlacklistParam;
import com.shop.cereshop.app.service.buyer.BuyerUserBlacklistService;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.BuyerUserBlacklist;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.enums.blacklist.*;
import com.shop.cereshop.commons.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 用户黑名单
 * @author zdd
 * @date 2025/11/12 16:21
 * @version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BuyerUserBlacklistServiceImpl implements BuyerUserBlacklistService {

    private final BuyerUserBlacklistMapper buyerUserBlacklistMapper;
    private final CereBuyerUserService cereBuyerUserService;

    @Override
    public Result<PageInfo<BuyerBlacklistVO>> getBlacklistPage(QueryBlacklistParam param) {
        try {
            QueryBlacklistDTO queryDTO = new QueryBlacklistDTO();
            if (param.getPageNum() == null || param.getPageNum() < 1) {
                queryDTO.setPageNum(1);
            }
            if (param.getPageSize() == null || param.getPageSize() < 1) {
                queryDTO.setPageSize(10);
            }
            // 只查询有效的
            queryDTO.setStatus(BlacklistStatus.ACTIVE.getCode());
            queryDTO.setBuyerUserId(param.getBuyerUserId());

            // 查询数据
            List<BuyerBlacklistVO> list = buyerUserBlacklistMapper.selectBlacklistPage(queryDTO);
            int total = buyerUserBlacklistMapper.countByCondition(queryDTO);

            // 构建分页结果
            PageInfo<BuyerBlacklistVO> pageInfo = new PageInfo<>();
            pageInfo.setList(list);
            pageInfo.setTotal((long) total);
            pageInfo.setPageNum(param.getPageNum());
            pageInfo.setPageSize(param.getPageSize());
            pageInfo.setPages((int) Math.ceil((double) total / param.getPageSize()));

            return new Result<>(pageInfo);
        } catch (Exception e) {
            log.error("查询黑名单分页失败: {}", param, e);
            return Result.failed(CoReturnFormat.FAIL, "查询黑名单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> addBlacklist(AddBlacklistParam param) {
        try {
            // 检查被拉黑用户是否存在
            CereBuyerUser blockedUser = cereBuyerUserService.selectByBuyerUserId(param.getBlockedUserId());
            if (blockedUser == null) {
                return new Result<>(CoReturnFormat.USER_NOT_EXIST);
            }
            log.info("用户 {} 拉黑用户 {} 拉黑场景 {}", param.getBuyerUserId(), param.getBlockedUserId(), param.getBlockScene());
            // 检查是否已存在有效黑名单
            LocalDateTime now = LocalDateTime.now();
            BuyerUserBlacklist blacklist = buyerUserBlacklistMapper.selectBlocklist(param.getBuyerUserId(), param.getBlockedUserId());
            if (blacklist != null) {
                blacklist.setUpdatedBy(param.getBuyerUserId());
                blacklist.setUpdatedTime(now);
                blacklist.setExpireTime(now.plusDays(36500));
                blacklist.setBlockScene(blacklist.getBlockScene() == 0 ? 0 : param.getBlockScene());
                int result = buyerUserBlacklistMapper.update(blacklist);
                if (result > 0) {
                    return Result.success();
                }
            } else {
                blacklist = new BuyerUserBlacklist();
                blacklist.setBuyerUserId(param.getBuyerUserId());
                blacklist.setBlockedUserId(param.getBlockedUserId());
                blacklist.setBlockScene(param.getBlockScene());
                blacklist.setCreatedBy(param.getBuyerUserId());
                blacklist.setUpdatedBy(param.getBuyerUserId());
                blacklist.setRelationType(BlacklistRelationType.USER_TO_USER.getCode());
                blacklist.setBlockSource(BlockSourceType.MANUAL.getCode());
                blacklist.setStatus(BlacklistStatus.ACTIVE.getCode());
                blacklist.setBlockLevel(BlockLevelType.MILD.getCode());
                blacklist.setAutoUnblock(AutoUnblockType.NO.getCode());
                // 设置过期时间 (默认100年)
                blacklist.setExpireTime(now.plusDays(36500));
                blacklist.setUpdatedTime(now);
                int result = buyerUserBlacklistMapper.insert(blacklist);
                if (result > 0) {
                    return Result.success();
                }
            }
            return new Result<>(CoReturnFormat.SYS_ERROR);
        } catch (Exception e) {
            log.error("添加黑名单失败: userId={}, blockedUserId={}", param.getBuyerUserId(), param.getBlockedUserId(), e);
            return Result.failed(CoReturnFormat.SYS_ERROR, "添加黑名单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> removeBlacklist(Long buyerUserId, Long blockedUserId) {
        try {
            int result = buyerUserBlacklistMapper.removeFromBlacklist(buyerUserId, blockedUserId, buyerUserId);
            if (result > 0) {
                log.info("用户 {} 成功解除拉黑用户 {}", buyerUserId, blockedUserId);
                return Result.success();
            } else {
                return Result.failed(CoReturnFormat.FAIL, "黑名单不存在");
            }
        } catch (Exception e) {
            log.error("移除黑名单失败: buyerUserId={}, blockedUserId={}", buyerUserId, blockedUserId, e);
            return Result.failed(CoReturnFormat.SYS_ERROR, "移除黑名单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> batchRemoveBlacklist(Long buyerUserId, List<Long> blockedUserIds) {
        try {
            if (buyerUserId == null || blockedUserIds == null || blockedUserIds.isEmpty()) {
                return new Result<>(CoReturnFormat.PARAM_INVALID);
            }

            int result = buyerUserBlacklistMapper.batchRemoveFromBlacklist(buyerUserId, blockedUserIds, buyerUserId);
            if (result > 0) {
                log.info("用户 {} 批量解除拉黑 {} 个用户", buyerUserId, result);
                return Result.success();
            } else {
                return Result.failed(CoReturnFormat.FAIL, "黑名单不存在");
            }
        } catch (Exception e) {
            log.error("批量移除黑名单失败: buyerUserId={}, blockedUserIds={}", buyerUserId, blockedUserIds, e);
            return Result.failed(CoReturnFormat.SYS_ERROR, "批量移除黑名单失败");
        }
    }

    @Override
    public boolean isInBlacklist(Long buyerUserId, Long blockedUserId) {
        if (buyerUserId == null || blockedUserId == null) {
            return false;
        }
        int count = buyerUserBlacklistMapper.checkInBlacklist(buyerUserId, blockedUserId);
        return count > 0;
    }

    @Override
    public List<Long> getBlockedByUserId(Long blockedUserId) {
        if (blockedUserId == null) {
            return Collections.emptyList();
        }
        List<BuyerUserBlacklist> blacklists = buyerUserBlacklistMapper.selectBlockedByUserId(blockedUserId);
        return blacklists.stream()
                .map(BuyerUserBlacklist::getBuyerUserId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoUnblockExpiredBlacklists() {
        try {
            List<BuyerUserBlacklist> expiredBlacklists = buyerUserBlacklistMapper.selectExpiredBlacklists();
            if (!expiredBlacklists.isEmpty()) {
                List<Long> ids = expiredBlacklists.stream()
                        .map(BuyerUserBlacklist::getId)
                        .collect(Collectors.toList());
                // 已过期
                int result = buyerUserBlacklistMapper.batchUpdateStatus(ids, -1);
                log.info("自动解封 {} 个过期的黑名单记录", result);
            }
        } catch (Exception e) {
            log.error("自动解封黑名单失败", e);
        }
    }

    @Override
    public Map<String, Object> getBlacklistStats(Long userId) {
        if (userId == null) {
            return Collections.emptyMap();
        }

        Map<String, Object> stats = new HashMap<>();

        // 总拉黑数量
        int totalCount = buyerUserBlacklistMapper.countBlacklistByUserId(userId);
        stats.put("totalCount", totalCount);

        // 按场景统计
        QueryBlacklistParam param = new QueryBlacklistParam();
        param.setBuyerUserId(userId);

        // 可以添加更多统计维度
        // 私信拉黑数
        stats.put("chatCount", 0);
        // 评论拉黑数
        stats.put("commentCount", 0);

        return stats;
    }

}
